package control;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
import static com.sun.corba.se.spi.presentation.rmi.StubAdapter.request;
import entities.users.AdminUser;
import java.io.IOException;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.HttpConstraint;
import javax.servlet.annotation.ServletSecurity;
import javax.servlet.annotation.ServletSecurity.TransportGuarantee;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpSession;
import util.Info;
import util.ejb.AdminUserBeanInterface;

/**
 *
 * @author Marek
 */
@WebServlet(urlPatterns = {"/adminUsers.jsp"})
@ServletSecurity(
        @HttpConstraint(transportGuarantee = TransportGuarantee.CONFIDENTIAL, rolesAllowed = {"admin"}))
public class AdminUserServlet extends AbstractServlet1 {

    private enum Key {

        newUser,
        deleteUser,
        selectUser,
        editUser,
        closeUser
    }

    public enum SessionKey {

        entities,
        selectedEntity
    }

    @EJB
    AdminUserBeanInterface adminUserBean;

    @Override
    protected void construct(ServletConfig config, RegisterForms registerForms, RegisterActions registerActions) {
        config.setServletName(this.getClass().getName());
        config.setTemplateName("adminUsersTmpl.jsp");
        registerActions.registerAction(Key.newUser.name(), ActionKey.processActionOne);
        registerActions.registerAction(Key.deleteUser.name(), ActionKey.processActionTwo);
        registerActions.registerAction(Key.selectUser.name(), ActionKey.processActionThree);
        registerActions.registerAction(Key.closeUser.name(), ActionKey.processActionFour);
        registerActions.registerAction("orderBy", ActionKey.processActionFive);
        registerForms.registerForm(Key.editUser.toString(), FormKey.processFormOne);
        registerForms.registerForm("searchBy", FormKey.processFormTwo);
    }

    @Override
    protected void beforeExit(HttpSession session, RegisterParameter registerParam, RegisterError registerError) {
        session.removeAttribute(SessionKey.entities.name());
        session.removeAttribute(SessionKey.selectedEntity.name());
        session.removeAttribute("searchByAdminUser");
    }

    @Override
    protected void initSesionVars(HttpSession session, RegisterParameter params, RegisterError errors) throws ServletException, BreakProcessException, RedirectRequest, CleanServletRequest {
        session.setAttribute("searchByAdminUser", new AdminUser());
        session.setAttribute("orderByColumn","login");
        session.setAttribute("orderByDirection","ASC");
    }

    @Override
    protected void processActionOne(HttpSession session, RegisterParameter params, RegisterError errors) throws BreakProcessException, RedirectRequest, CleanServletRequest {
        adminUserBean.createAdminUser();
    }

    @Override
    protected void processActionTwo(HttpSession session, RegisterParameter params, RegisterError errors) throws BreakProcessException, RedirectRequest, CleanServletRequest {
        //TODO: Try catch
        System.out.println("TESTESTEST" + (String) params.readParameter("id")[0]);
        Long adminUserId = new Long((String) params.readParameter("id")[0]);
        adminUserBean.deleteAdminUser(adminUserBean.getAdminUser(adminUserId));
    }

    @Override
    protected void processActionThree(HttpSession session, RegisterParameter params, RegisterError errors) throws BreakProcessException, RedirectRequest, CleanServletRequest {
        Long adminUserId = new Long((String) params.readParameter("id")[0]);
        AdminUser adminUser = adminUserBean.getAdminUser(adminUserId);
        session.setAttribute(SessionKey.selectedEntity.name(), adminUser);

    }

    @Override
    protected void processActionFour(HttpSession session, RegisterParameter params, RegisterError errors) throws BreakProcessException, RedirectRequest, CleanServletRequest {
        session.removeAttribute(SessionKey.selectedEntity.name());
    }

    @Override
    protected void processActionFive(HttpSession session, RegisterParameter params, RegisterError errors) throws BreakProcessException, RedirectRequest, CleanServletRequest {
        String columnName = (String) params.readParameter("columnName")[0];
        char[] chars = columnName.toCharArray();
        chars[0] = Character.toUpperCase(chars[0]);
        //TODO: While testing, check if this security constraint is working correctly
        if (Info.descriptionExist(AdminUser.class, "get" + (new String(chars)))) {
            session.setAttribute("orderByColumn", columnName);
            List<AdminUser> adminUsers;
            if (session.getAttribute("orderByDirection") == null) {
                session.setAttribute("orderByDirection", "ASC");
            } else if (session.getAttribute("orderByDirection").equals("ASC")) {
                session.setAttribute("orderByDirection", "DESC");
            } else if (session.getAttribute("orderByDirection").equals("DESC")) {
                session.setAttribute("orderByDirection", "ASC");
            } else {
                return;
            }
            System.out.println("action five" + columnName);
        }
    }

    @Override
    protected void processFormOne(HttpSession session, RegisterParameter params, RegisterError errors) throws BreakProcessException, RedirectRequest, CleanServletRequest {
        AdminUser adminUser = (AdminUser) FormGenerator.updateEntity((AdminUser) session.getAttribute(SessionKey.selectedEntity.name()), params);
        adminUserBean.updateAdminUser(adminUser);
        session.setAttribute(SessionKey.selectedEntity.name(), adminUser);

    }

    @Override
    protected void processFormTwo(HttpSession session, RegisterParameter params, RegisterError errors) throws BreakProcessException, RedirectRequest, CleanServletRequest {
        AdminUser searchByAdminUser = (AdminUser) FormGenerator.updateEntity(new AdminUser(), params);
        session.setAttribute("searchByAdminUser", searchByAdminUser);
        System.out.println("I work correctly :-)");

    }

    @Override
    protected void load(HttpSession session, RegisterParameter params, RegisterError errors) throws ServletException, IOException, BreakProcessException, RedirectRequest, CleanServletRequest {
        //This orderBy session attribute probably should be saved in AbstractServlet1 instead of the subclasses, becouse every subclass will need to use the same code :-)
        String orderBy = (String) session.getAttribute("orderByColumn");
        String direction = (String) session.getAttribute("orderByDirection");
        AdminUser adminUser = (AdminUser) session.getAttribute("searchByAdminUser");
        if (orderBy != null && direction != null) {
            List<AdminUser> adminUsers = adminUserBean.getAdminUsers(orderBy, direction, adminUser);
            session.setAttribute(SessionKey.entities.name(), adminUsers);
        } 
    }

    @Override
    protected void save(HttpSession session, RegisterParameter params, RegisterError errors) throws ServletException, IOException, BreakProcessException, RedirectRequest, CleanServletRequest {
    }
}
